package com.qq.clone.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import java.time.OffsetDateTime;

// 数据库插入自动填入时间字段
@Configuration
@Slf4j
public class CommonMetaObjectHandler implements MetaObjectHandler {
    public CommonMetaObjectHandler() {
        log.info("CommonMetaObjectHandler init");
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        // created_at: 如果为空，填充当前时间
        if (getFieldValByName("createdAt", metaObject) == null) {
            setFieldValByName("createdAt", OffsetDateTime.now(), metaObject);
        }
        // created_at -> 也可以支持驼峰 createdAt / 下划线 created_at
        if (getFieldValByName("created_at", metaObject) == null) {
            setFieldValByName("created_at", OffsetDateTime.now(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {

    }
}